package com.netty.client.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.netty.client.QbbClient;
import com.netty.client.pool.active.ThreadActiveBean;
import com.netty.client.pool.active.ThreadActiveTask;
import com.qbb.client.bean.active.SocketBean;
import com.qbb.client.bean.result.SocketResultBean;
import com.qbb.client.exception.HandlerException;
import com.qbb.client.exception.NettyTimeOutException;
import com.qbb.client.util.DateUtil;

/**
 * 类说明
 * 
 * @author chenhuaiao
 * @version V1.0 创建时间：Mar 19, 2015 4:43:55 PM
 */
public class ClientTimeOutHandler extends ChannelInboundHandlerAdapter {
	private static Log log = LogFactory.getLog(ClientTimeOutHandler.class);

	private boolean isRead = false;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		Date beginDate = new Date();
		String beginStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(beginDate);
		log.info("QbbClient channelRead begin[" + beginStr + "]");

		isRead = true;
		try {
			SocketResultBean resultBean = null;
			try {
				resultBean = SocketBean.getResultBean(msg);
			} catch (Exception e) {
				HandlerException.error(e);
			}

			String uuidStr = resultBean.getUuidString();
			uuidStr = uuidStr != null ? uuidStr : "";

			QbbClient.readMaps.put(uuidStr, resultBean);
		} catch (Exception e) {
			HandlerException.error(e);
		} finally {
			ctx.close();

			Date endDate = new Date();
			String endStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(endDate);
			log.info("QbbClient channelRead end[" + endStr + "]");
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Date beginDate = new Date();
		String beginStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(beginDate);
		log.info("QbbClient channelActive begin[" + beginStr + "]");

		ThreadActiveTask.submit(new ThreadActiveBean(ctx));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		Date beginDate = new Date();
		String beginStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(beginDate);
		log.info("QbbClient exceptionCaught begin[" + beginStr + "]");

		cause.printStackTrace();
		ctx.close();

		Date endDate = new Date();
		String endStr = DateUtil.date_YYYY_MM_DD_MM_HH_SS(endDate);
		log.info("QbbClient exceptionCaught end[" + endStr + "]");
	}

	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		if (!isRead) {
			ctx.close();
			throw new NettyTimeOutException("netty client cant connection");
		}
	}
}